<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>ArrayBuffer | 知识库</title>
    <meta name="generator" content="VuePress 1.9.9">
    <link rel="icon" href="/noteslibrary/img/favicon.ico">
    <meta name="description" content="Java后端技术博客,专注Java后端学习与总结。HTML,CSS,JavaScript,TypeScript,JavaSE,Python,Vue,React,Node,Git,Github等技术文章。">
    <meta name="keywords" content="后端博客,个人技术博客,后端,后端开发,后端框架,后端面试题,技术文档,学习,面试,HTML,CSS,JavaScript,TypeScript,JavaSE,Python,Vue,React,Node,Git,Github">
    <meta name="theme-color" content="#11a8cd">
    
    <link rel="preload" href="/noteslibrary/assets/css/0.styles.2500ff6d.css" as="style"><link rel="preload" href="/noteslibrary/assets/js/app.dc0c3d24.js" as="script"><link rel="preload" href="/noteslibrary/assets/js/2.a664539c.js" as="script"><link rel="preload" href="/noteslibrary/assets/js/71.aff6ef6b.js" as="script"><link rel="prefetch" href="/noteslibrary/assets/js/10.bab1a8b9.js"><link rel="prefetch" href="/noteslibrary/assets/js/100.245d2d1d.js"><link rel="prefetch" href="/noteslibrary/assets/js/101.9d1c6c13.js"><link rel="prefetch" href="/noteslibrary/assets/js/102.d187686f.js"><link rel="prefetch" href="/noteslibrary/assets/js/103.b0e7acf6.js"><link rel="prefetch" href="/noteslibrary/assets/js/104.895c9e53.js"><link rel="prefetch" href="/noteslibrary/assets/js/105.235036be.js"><link rel="prefetch" href="/noteslibrary/assets/js/106.17a71ae1.js"><link rel="prefetch" href="/noteslibrary/assets/js/107.256ceb5d.js"><link rel="prefetch" href="/noteslibrary/assets/js/108.57832d85.js"><link rel="prefetch" href="/noteslibrary/assets/js/109.f8b1d1c7.js"><link rel="prefetch" href="/noteslibrary/assets/js/11.2c69801a.js"><link rel="prefetch" href="/noteslibrary/assets/js/110.f3ce6a68.js"><link rel="prefetch" href="/noteslibrary/assets/js/111.bdfd28f4.js"><link rel="prefetch" href="/noteslibrary/assets/js/112.878f599c.js"><link rel="prefetch" href="/noteslibrary/assets/js/113.0efa07cf.js"><link rel="prefetch" href="/noteslibrary/assets/js/114.c7aba251.js"><link rel="prefetch" href="/noteslibrary/assets/js/115.8b2e628d.js"><link rel="prefetch" href="/noteslibrary/assets/js/116.3392d8ba.js"><link rel="prefetch" href="/noteslibrary/assets/js/117.310538d0.js"><link rel="prefetch" href="/noteslibrary/assets/js/118.81eb015b.js"><link rel="prefetch" href="/noteslibrary/assets/js/12.e77f5a18.js"><link rel="prefetch" href="/noteslibrary/assets/js/13.d24d0054.js"><link rel="prefetch" href="/noteslibrary/assets/js/14.f29d4d33.js"><link rel="prefetch" href="/noteslibrary/assets/js/15.8694e081.js"><link rel="prefetch" href="/noteslibrary/assets/js/16.03ffb143.js"><link rel="prefetch" href="/noteslibrary/assets/js/17.83edd7b9.js"><link rel="prefetch" href="/noteslibrary/assets/js/18.58ca4447.js"><link rel="prefetch" href="/noteslibrary/assets/js/19.e136d5c2.js"><link rel="prefetch" href="/noteslibrary/assets/js/20.fd3961b6.js"><link rel="prefetch" href="/noteslibrary/assets/js/21.207406c6.js"><link rel="prefetch" href="/noteslibrary/assets/js/22.b8738ce2.js"><link rel="prefetch" href="/noteslibrary/assets/js/23.33e4529d.js"><link rel="prefetch" href="/noteslibrary/assets/js/24.ab5493c5.js"><link rel="prefetch" href="/noteslibrary/assets/js/25.2506ce48.js"><link rel="prefetch" href="/noteslibrary/assets/js/26.7e6a9c14.js"><link rel="prefetch" href="/noteslibrary/assets/js/27.e7b4e92a.js"><link rel="prefetch" href="/noteslibrary/assets/js/28.7ad46ba6.js"><link rel="prefetch" href="/noteslibrary/assets/js/29.81666f41.js"><link rel="prefetch" href="/noteslibrary/assets/js/3.8f13cd17.js"><link rel="prefetch" href="/noteslibrary/assets/js/30.07ada09b.js"><link rel="prefetch" href="/noteslibrary/assets/js/31.f271c8cf.js"><link rel="prefetch" href="/noteslibrary/assets/js/32.2350914c.js"><link rel="prefetch" href="/noteslibrary/assets/js/33.9d7bfb77.js"><link rel="prefetch" href="/noteslibrary/assets/js/34.6fcf6f6b.js"><link rel="prefetch" href="/noteslibrary/assets/js/35.0c3a88fb.js"><link rel="prefetch" href="/noteslibrary/assets/js/36.574ca92a.js"><link rel="prefetch" href="/noteslibrary/assets/js/37.72e38074.js"><link rel="prefetch" href="/noteslibrary/assets/js/38.16d408fb.js"><link rel="prefetch" href="/noteslibrary/assets/js/39.63abc4a8.js"><link rel="prefetch" href="/noteslibrary/assets/js/4.3e68fc94.js"><link rel="prefetch" href="/noteslibrary/assets/js/40.ca2bdd48.js"><link rel="prefetch" href="/noteslibrary/assets/js/41.f82c80ec.js"><link rel="prefetch" href="/noteslibrary/assets/js/42.d1b8f579.js"><link rel="prefetch" href="/noteslibrary/assets/js/43.d3fd6260.js"><link rel="prefetch" href="/noteslibrary/assets/js/44.491f9afa.js"><link rel="prefetch" href="/noteslibrary/assets/js/45.1ee0d084.js"><link rel="prefetch" href="/noteslibrary/assets/js/46.a3e0be1f.js"><link rel="prefetch" href="/noteslibrary/assets/js/47.647908d1.js"><link rel="prefetch" href="/noteslibrary/assets/js/48.9658b8b0.js"><link rel="prefetch" href="/noteslibrary/assets/js/49.8f4b8327.js"><link rel="prefetch" href="/noteslibrary/assets/js/5.a0a97ccd.js"><link rel="prefetch" href="/noteslibrary/assets/js/50.f46d1433.js"><link rel="prefetch" href="/noteslibrary/assets/js/51.f1b784a0.js"><link rel="prefetch" href="/noteslibrary/assets/js/52.cce45956.js"><link rel="prefetch" href="/noteslibrary/assets/js/53.d66dabe3.js"><link rel="prefetch" href="/noteslibrary/assets/js/54.384b864b.js"><link rel="prefetch" href="/noteslibrary/assets/js/55.47ed19f2.js"><link rel="prefetch" href="/noteslibrary/assets/js/56.193cd456.js"><link rel="prefetch" href="/noteslibrary/assets/js/57.e6ea1f8c.js"><link rel="prefetch" href="/noteslibrary/assets/js/58.97fd2330.js"><link rel="prefetch" href="/noteslibrary/assets/js/59.b0c3d9ea.js"><link rel="prefetch" href="/noteslibrary/assets/js/6.50cbd75f.js"><link rel="prefetch" href="/noteslibrary/assets/js/60.d01d0651.js"><link rel="prefetch" href="/noteslibrary/assets/js/61.385e9bae.js"><link rel="prefetch" href="/noteslibrary/assets/js/62.a93fa4c8.js"><link rel="prefetch" href="/noteslibrary/assets/js/63.f72a2142.js"><link rel="prefetch" href="/noteslibrary/assets/js/64.3bf0b024.js"><link rel="prefetch" href="/noteslibrary/assets/js/65.cb1cb3bb.js"><link rel="prefetch" href="/noteslibrary/assets/js/66.4c9ff8cd.js"><link rel="prefetch" href="/noteslibrary/assets/js/67.2fc17900.js"><link rel="prefetch" href="/noteslibrary/assets/js/68.fd3ee410.js"><link rel="prefetch" href="/noteslibrary/assets/js/69.682be05d.js"><link rel="prefetch" href="/noteslibrary/assets/js/7.80203dee.js"><link rel="prefetch" href="/noteslibrary/assets/js/70.29428a45.js"><link rel="prefetch" href="/noteslibrary/assets/js/72.fe7572e0.js"><link rel="prefetch" href="/noteslibrary/assets/js/73.e52bc1a7.js"><link rel="prefetch" href="/noteslibrary/assets/js/74.5e72ee84.js"><link rel="prefetch" href="/noteslibrary/assets/js/75.5a5bba64.js"><link rel="prefetch" href="/noteslibrary/assets/js/76.70d6ff7c.js"><link rel="prefetch" href="/noteslibrary/assets/js/77.1db1c302.js"><link rel="prefetch" href="/noteslibrary/assets/js/78.137c92e8.js"><link rel="prefetch" href="/noteslibrary/assets/js/79.8455d34b.js"><link rel="prefetch" href="/noteslibrary/assets/js/8.9e13e493.js"><link rel="prefetch" href="/noteslibrary/assets/js/80.127f3a4e.js"><link rel="prefetch" href="/noteslibrary/assets/js/81.191d3614.js"><link rel="prefetch" href="/noteslibrary/assets/js/82.6ae31745.js"><link rel="prefetch" href="/noteslibrary/assets/js/83.640cd3d7.js"><link rel="prefetch" href="/noteslibrary/assets/js/84.22c036e2.js"><link rel="prefetch" href="/noteslibrary/assets/js/85.692cd496.js"><link rel="prefetch" href="/noteslibrary/assets/js/86.793e38a7.js"><link rel="prefetch" href="/noteslibrary/assets/js/87.eb27f1d6.js"><link rel="prefetch" href="/noteslibrary/assets/js/88.6d48c75e.js"><link rel="prefetch" href="/noteslibrary/assets/js/89.a798bacb.js"><link rel="prefetch" href="/noteslibrary/assets/js/9.7e864ff7.js"><link rel="prefetch" href="/noteslibrary/assets/js/90.e814aadc.js"><link rel="prefetch" href="/noteslibrary/assets/js/91.5c132772.js"><link rel="prefetch" href="/noteslibrary/assets/js/92.d0d1984d.js"><link rel="prefetch" href="/noteslibrary/assets/js/93.bbc81ca6.js"><link rel="prefetch" href="/noteslibrary/assets/js/94.242fbc29.js"><link rel="prefetch" href="/noteslibrary/assets/js/95.f7232d68.js"><link rel="prefetch" href="/noteslibrary/assets/js/96.440e6bbe.js"><link rel="prefetch" href="/noteslibrary/assets/js/97.a8ad3aa8.js"><link rel="prefetch" href="/noteslibrary/assets/js/98.e9a01f98.js"><link rel="prefetch" href="/noteslibrary/assets/js/99.e024f354.js">
    <link rel="stylesheet" href="/noteslibrary/assets/css/0.styles.2500ff6d.css">
  </head>
  <body class="theme-mode-light">
    <div id="app" data-server-rendered="true"><div class="theme-container sidebar-open have-rightmenu"><header class="navbar blur"><div title="目录" class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/noteslibrary/" class="home-link router-link-active"><img src="/noteslibrary/img/EB-logo.png" alt="知识库" class="logo"> <span class="site-name can-hide">知识库</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/noteslibrary/" class="nav-link">首页</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="基础" class="dropdown-title"><a href="/noteslibrary/basis/" class="link-title">基础</a> <span class="title" style="display:none;">基础</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>笔记</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《计算机网络》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《计算机组成原理》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《操作系统》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《数据结构》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《算法》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《设计模式》</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="前端" class="dropdown-title"><a href="/noteslibrary/fontend/" class="link-title">前端</a> <span class="title" style="display:none;">前端</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>笔记</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/0796ba76b4b55368.html" class="nav-link">《JS笔记》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/f344d070a1031ef7.html" class="nav-link">《ES6笔记》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/note/vue/" class="nav-link">《Vue笔记》</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="后端" class="dropdown-title"><a href="/noteslibrary/backend/" class="link-title">后端</a> <span class="title" style="display:none;">后端</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>JavaEE框架</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/d0b17d/" class="nav-link">《DAO全家桶》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/a9ac80/" class="nav-link">《Spring全家桶》</a></li></ul></li><li class="dropdown-item"><h4>BigData框架</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/a2ba314746bfdbdd/404" class="nav-link">《Hadoop生态》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/a2ba314746bfdbdd/404" class="nav-link">《Spark生态》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/a2ba314746bfdbdd/404" class="nav-link">《Flink生态》</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="数据库" class="dropdown-title"><a href="/noteslibrary/database/" class="link-title">数据库</a> <span class="title" style="display:none;">数据库</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4></h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/32e9fd/" class="nav-link">MySQL</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="工具" class="dropdown-title"><a href="/noteslibrary/tools/" class="link-title">工具</a> <span class="title" style="display:none;">工具</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4></h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/3ac065/" class="nav-link">Maven</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/5760de/" class="nav-link">Git</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="收藏" class="dropdown-title"><a href="/noteslibrary/collect/" class="link-title">收藏</a> <span class="title" style="display:none;">收藏</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4></h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/50c072/" class="nav-link">博客收藏</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="其他" class="dropdown-title"><a href="/noteslibrary/others/" class="link-title">其他</a> <span class="title" style="display:none;">其他</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>博客部署</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/db737d/" class="nav-link">Hexo</a></li></ul></li><li class="dropdown-item"><h4>系统安装</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/3ac066/" class="nav-link">系统安装</a></li></ul></li><li class="dropdown-item"><h4>idea快捷键</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/111c73/" class="nav-link">idea快捷键</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/noteslibrary/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/noteslibrary/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/noteslibrary/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/noteslibrary/archives/" class="nav-link">归档</a></li></ul></div></div> <a href="https://github.com/lcfqzd/vuepress-theme-vdoing" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <div class="sidebar-hover-trigger"></div> <aside class="sidebar" style="display:none;"><!----> <nav class="nav-links"><div class="nav-item"><a href="/noteslibrary/" class="nav-link">首页</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="基础" class="dropdown-title"><a href="/noteslibrary/basis/" class="link-title">基础</a> <span class="title" style="display:none;">基础</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>笔记</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《计算机网络》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《计算机组成原理》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《操作系统》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《数据结构》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《算法》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/9a7ee40fc232253e/" class="nav-link">《设计模式》</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="前端" class="dropdown-title"><a href="/noteslibrary/fontend/" class="link-title">前端</a> <span class="title" style="display:none;">前端</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>笔记</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/0796ba76b4b55368.html" class="nav-link">《JS笔记》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/f344d070a1031ef7.html" class="nav-link">《ES6笔记》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/note/vue/" class="nav-link">《Vue笔记》</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="后端" class="dropdown-title"><a href="/noteslibrary/backend/" class="link-title">后端</a> <span class="title" style="display:none;">后端</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>JavaEE框架</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/d0b17d/" class="nav-link">《DAO全家桶》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/a9ac80/" class="nav-link">《Spring全家桶》</a></li></ul></li><li class="dropdown-item"><h4>BigData框架</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/a2ba314746bfdbdd/404" class="nav-link">《Hadoop生态》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/a2ba314746bfdbdd/404" class="nav-link">《Spark生态》</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/a2ba314746bfdbdd/404" class="nav-link">《Flink生态》</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="数据库" class="dropdown-title"><a href="/noteslibrary/database/" class="link-title">数据库</a> <span class="title" style="display:none;">数据库</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4></h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/32e9fd/" class="nav-link">MySQL</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="工具" class="dropdown-title"><a href="/noteslibrary/tools/" class="link-title">工具</a> <span class="title" style="display:none;">工具</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4></h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/3ac065/" class="nav-link">Maven</a></li><li class="dropdown-subitem"><a href="/noteslibrary/pages/5760de/" class="nav-link">Git</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="收藏" class="dropdown-title"><a href="/noteslibrary/collect/" class="link-title">收藏</a> <span class="title" style="display:none;">收藏</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4></h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/50c072/" class="nav-link">博客收藏</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="其他" class="dropdown-title"><a href="/noteslibrary/others/" class="link-title">其他</a> <span class="title" style="display:none;">其他</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>博客部署</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/db737d/" class="nav-link">Hexo</a></li></ul></li><li class="dropdown-item"><h4>系统安装</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/3ac066/" class="nav-link">系统安装</a></li></ul></li><li class="dropdown-item"><h4>idea快捷键</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/noteslibrary/pages/111c73/" class="nav-link">idea快捷键</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/noteslibrary/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/noteslibrary/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/noteslibrary/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/noteslibrary/archives/" class="nav-link">归档</a></li></ul></div></div> <a href="https://github.com/lcfqzd/vuepress-theme-vdoing" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>JavaScript笔记</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>ES6笔记</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/noteslibrary/pages/f344d070a1031ef7/" class="sidebar-link">ECMAScript 6 简介</a></li><li><a href="/noteslibrary/pages/c1edd70a6b7c7872/" class="sidebar-link">let 和 const 命令</a></li><li><a href="/noteslibrary/pages/b1ab10a62f7564da/" class="sidebar-link">变量的解构赋值</a></li><li><a href="/noteslibrary/pages/ca89eca8adeba5f4/" class="sidebar-link">字符串的扩展</a></li><li><a href="/noteslibrary/pages/a650b4a0ebfc9350/" class="sidebar-link">字符串的新增方法</a></li><li><a href="/noteslibrary/pages/0473261a6ab0ee8c/" class="sidebar-link">正则的扩展</a></li><li><a href="/noteslibrary/pages/5dfea9a0f2d1a392/" class="sidebar-link">数值的扩展</a></li><li><a href="/noteslibrary/pages/8ed309d668b20264/" class="sidebar-link">函数的扩展</a></li><li><a href="/noteslibrary/pages/e34009d60d8bc4b2/" class="sidebar-link">数组的扩展</a></li><li><a href="/noteslibrary/pages/b5e3e0a0ff6e9c25/" class="sidebar-link">对象的扩展</a></li><li><a href="/noteslibrary/pages/e85e68947502cf90/" class="sidebar-link">对象的新增方法</a></li><li><a href="/noteslibrary/pages/02c86eb2792f3262/" class="sidebar-link">Symbol</a></li><li><a href="/noteslibrary/pages/0c21dae358fca16b/" class="sidebar-link">Set 和 Map 数据结构</a></li><li><a href="/noteslibrary/pages/f56ec2ab97d60483/" class="sidebar-link">Proxy</a></li><li><a href="/noteslibrary/pages/74de3e45e4491e95/" class="sidebar-link">Reflect</a></li><li><a href="/noteslibrary/pages/2810ae8985e9bd52/" class="sidebar-link">Promise 对象</a></li><li><a href="/noteslibrary/pages/48df907ad3570f3d/" class="sidebar-link">Iterator 和 for-of 循环</a></li><li><a href="/noteslibrary/pages/718b48ed9ce0adce/" class="sidebar-link">Generator 函数的语法</a></li><li><a href="/noteslibrary/pages/75af7031eb66847b/" class="sidebar-link">Generator 函数的异步应用</a></li><li><a href="/noteslibrary/pages/3777253e65bac487/" class="sidebar-link">async 函数</a></li><li><a href="/noteslibrary/pages/e831e1593c82bbe0/" class="sidebar-link">Class 的基本语法</a></li><li><a href="/noteslibrary/pages/83f8c3a0cd87dd83/" class="sidebar-link">Class 的继承</a></li><li><a href="/noteslibrary/pages/efe2fb04eb8ac5fb/" class="sidebar-link">Module 的语法</a></li><li><a href="/noteslibrary/pages/a79ca2e64ceae213/" class="sidebar-link">Module 的加载实现</a></li><li><a href="/noteslibrary/pages/984bf549204bb266/" class="sidebar-link">编程风格</a></li><li><a href="/noteslibrary/pages/32c35f7651d6e58e/" class="sidebar-link">读懂 ECMAScript 规格</a></li><li><a href="/noteslibrary/pages/16121351be68691b/" class="sidebar-link">异步遍历器</a></li><li><a href="/noteslibrary/pages/a2ba314746bfdbdd/" aria-current="page" class="active sidebar-link">ArrayBuffer</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level2"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#arraybuffer-对象" class="sidebar-link">ArrayBuffer 对象</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#概述" class="sidebar-link">概述</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#arraybuffer-prototype-bytelength" class="sidebar-link">ArrayBuffer.prototype.byteLength</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#arraybuffer-prototype-slice" class="sidebar-link">ArrayBuffer.prototype.slice()</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#arraybuffer-isview" class="sidebar-link">ArrayBuffer.isView()</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-视图" class="sidebar-link">TypedArray 视图</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#概述-2" class="sidebar-link">概述</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#构造函数" class="sidebar-link">构造函数</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#数组方法" class="sidebar-link">数组方法</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#字节序" class="sidebar-link">字节序</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#bytes-per-element-属性" class="sidebar-link">BYTESPERELEMENT 属性</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#arraybuffer-与字符串的互相转换" class="sidebar-link">ArrayBuffer 与字符串的互相转换</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#溢出" class="sidebar-link">溢出</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-prototype-buffer" class="sidebar-link">TypedArray.prototype.buffer</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-prototype-bytelength-typedarray-prototype-byteoffset" class="sidebar-link">TypedArray.prototype.byteLength，TypedArray.prototype.byteOffset</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-prototype-length" class="sidebar-link">TypedArray.prototype.length</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-prototype-set" class="sidebar-link">TypedArray.prototype.set()</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-prototype-subarray" class="sidebar-link">TypedArray.prototype.subarray()</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-prototype-slice" class="sidebar-link">TypedArray.prototype.slice()</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-of" class="sidebar-link">TypedArray.of()</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#typedarray-from" class="sidebar-link">TypedArray.from()</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#复合视图" class="sidebar-link">复合视图</a></li><li class="sidebar-sub-header level2"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#dataview-视图" class="sidebar-link">DataView 视图</a></li><li class="sidebar-sub-header level2"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#二进制数组的应用" class="sidebar-link">二进制数组的应用</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#ajax" class="sidebar-link">AJAX</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#canvas" class="sidebar-link">Canvas</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#websocket" class="sidebar-link">WebSocket</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#fetch-api" class="sidebar-link">Fetch API</a></li><li class="sidebar-sub-header level3"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#file-api" class="sidebar-link">File API</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#sharedarraybuffer" class="sidebar-link">SharedArrayBuffer</a></li><li class="sidebar-sub-header level2"><a href="/noteslibrary/pages/a2ba314746bfdbdd/#atomics-对象" class="sidebar-link">Atomics 对象</a></li></ul></li><li><a href="/noteslibrary/pages/7188882b8d65af1b/" class="sidebar-link">最新提案</a></li><li><a href="/noteslibrary/pages/e97bc1e5626b082c/" class="sidebar-link">装饰器</a></li><li><a href="/noteslibrary/pages/1cf50330655efc69/" class="sidebar-link">函数式编程</a></li><li><a href="/noteslibrary/pages/6a8e2dc558da1b39/" class="sidebar-link">Mixin</a></li><li><a href="/noteslibrary/pages/8e8f80f69b775a56/" class="sidebar-link">SIMD</a></li><li><a href="/noteslibrary/pages/ea6f3b870f6dab69/" class="sidebar-link">参考链接</a></li></ul></section></li></ul> </aside> <div><main class="page"><div class="theme-vdoing-wrapper "><div class="articleInfo-wrap" data-v-06225672><div class="articleInfo" data-v-06225672><ul class="breadcrumbs" data-v-06225672><li data-v-06225672><a href="/noteslibrary/" title="首页" class="iconfont icon-home router-link-active" data-v-06225672></a></li> <li data-v-06225672><a href="/noteslibrary/fontend/#前端" data-v-06225672>前端</a></li><li data-v-06225672><a href="/noteslibrary/fontend/#ES6笔记" data-v-06225672>ES6笔记</a></li></ul> <div class="info" data-v-06225672><div title="作者" class="author iconfont icon-touxiang" data-v-06225672><a href="javascript:;" data-v-06225672>阮一峰</a></div> <div title="创建时间" class="date iconfont icon-riqi" data-v-06225672><a href="javascript:;" data-v-06225672>2020-02-09</a></div> <!----></div></div></div> <!----> <div class="content-wrapper"><div class="right-menu-wrapper"><div class="right-menu-margin"><div class="right-menu-title">目录</div> <div class="right-menu-content"></div></div></div> <h1><img src="">ArrayBuffer<!----></h1> <!----> <div class="theme-vdoing-content content__default"><h1 id="arraybuffer"><a href="#arraybuffer" class="header-anchor">#</a> ArrayBuffer</h1> <p><code>ArrayBuffer</code>对象、<code>TypedArray</code>视图和<code>DataView</code>视图是 JavaScript 操作二进制数据的一个接口。这些对象早就存在，属于独立的规格（2011 年 2 月发布），ES6 将它们纳入了 ECMAScript 规格，并且增加了新的方法。它们都是以数组的语法处理二进制数据，所以统称为二进制数组。

这个接口的原始设计目的，与 WebGL 项目有关。所谓 WebGL，就是指浏览器与显卡之间的通信接口，为了满足 JavaScript 与显卡之间大量的、实时的数据交换，它们之间的数据通信必须是二进制的，而不能是传统的文本格式。文本格式传递一个 32 位整数，两端的 JavaScript 脚本与显卡都要进行格式转化，将非常耗时。这时要是存在一种机制，可以像 C 语言那样，直接操作字节，将 4 个字节的 32 位整数，以二进制形式原封不动地送入显卡，脚本的性能就会大幅提升。</p> <p>二进制数组就是在这种背景下诞生的。它很像 C 语言的数组，允许开发者以数组下标的形式，直接操作内存，大大增强了 JavaScript 处理二进制数据的能力，使得开发者有可能通过 JavaScript 与操作系统的原生接口进行二进制通信。</p> <p>二进制数组由三类对象组成。</p> <p><strong>（1）<code>ArrayBuffer</code>对象</strong>：代表内存之中的一段二进制数据，可以通过“视图”进行操作。“视图”部署了数组接口，这意味着，可以用数组的方法操作内存。</p> <p><strong>（2）<code>TypedArray</code>视图</strong>：共包括 9 种类型的视图，比如<code>Uint8Array</code>（无符号 8 位整数）数组视图, <code>Int16Array</code>（16 位整数）数组视图, <code>Float32Array</code>（32 位浮点数）数组视图等等。</p> <p><strong>（3）<code>DataView</code>视图</strong>：可以自定义复合格式的视图，比如第一个字节是 Uint8（无符号 8 位整数）、第二、三个字节是 Int16（16 位整数）、第四个字节开始是 Float32（32 位浮点数）等等，此外还可以自定义字节序。</p> <p>简单说，<code>ArrayBuffer</code>对象代表原始的二进制数据，<code>TypedArray</code>视图用来读写简单类型的二进制数据，<code>DataView</code>视图用来读写复杂类型的二进制数据。</p> <p><code>TypedArray</code>视图支持的数据类型一共有 9 种（<code>DataView</code>视图支持除<code>Uint8C</code>以外的其他 8 种）。</p> <table><thead><tr><th>数据类型</th> <th>字节长度</th> <th>含义</th> <th>对应的 C 语言类型</th></tr></thead> <tbody><tr><td>Int8</td> <td>1</td> <td>8 位带符号整数</td> <td>signed char</td></tr> <tr><td>Uint8</td> <td>1</td> <td>8 位不带符号整数</td> <td>unsigned char</td></tr> <tr><td>Uint8C</td> <td>1</td> <td>8 位不带符号整数（自动过滤溢出）</td> <td>unsigned char</td></tr> <tr><td>Int16</td> <td>2</td> <td>16 位带符号整数</td> <td>short</td></tr> <tr><td>Uint16</td> <td>2</td> <td>16 位不带符号整数</td> <td>unsigned short</td></tr> <tr><td>Int32</td> <td>4</td> <td>32 位带符号整数</td> <td>int</td></tr> <tr><td>Uint32</td> <td>4</td> <td>32 位不带符号的整数</td> <td>unsigned int</td></tr> <tr><td>Float32</td> <td>4</td> <td>32 位浮点数</td> <td>float</td></tr> <tr><td>Float64</td> <td>8</td> <td>64 位浮点数</td> <td>double</td></tr></tbody></table> <p>注意，二进制数组并不是真正的数组，而是类似数组的对象。</p> <p>很多浏览器操作的 API，用到了二进制数组操作二进制数据，下面是其中的几个。</p> <ul><li><a href="#canvas">Canvas</a></li> <li><a href="#fetch-api">Fetch API</a></li> <li><a href="#file-api">File API</a></li> <li><a href="#websocket">WebSockets</a></li> <li><a href="#ajax">XMLHttpRequest</a></li></ul> <h2 id="arraybuffer-对象"><a href="#arraybuffer-对象" class="header-anchor">#</a> ArrayBuffer 对象</h2> <h3 id="概述"><a href="#概述" class="header-anchor">#</a> 概述</h3> <p><code>ArrayBuffer</code>对象代表储存二进制数据的一段内存，它不能直接读写，只能通过视图（<code>TypedArray</code>视图和<code>DataView</code>视图)来读写，视图的作用是以指定格式解读二进制数据。</p> <p><code>ArrayBuffer</code>也是一个构造函数，可以分配一段可以存放数据的连续内存区域。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buf <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>上面代码生成了一段 32 字节的内存区域，每个字节的值默认都是 0。可以看到，<code>ArrayBuffer</code>构造函数的参数是所需要的内存大小（单位字节）。</p> <p>为了读写这段内容，需要为它指定视图。<code>DataView</code>视图的创建，需要提供<code>ArrayBuffer</code>对象实例作为参数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buf <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> dataView <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DataView</span><span class="token punctuation">(</span>buf<span class="token punctuation">)</span><span class="token punctuation">;</span>
dataView<span class="token punctuation">.</span><span class="token function">getUint8</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token comment">// 0</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>上面代码对一段 32 字节的内存，建立<code>DataView</code>视图，然后以不带符号的 8 位整数格式，从头读取 8 位二进制数据，结果得到 0，因为原始内存的<code>ArrayBuffer</code>对象，默认所有位都是 0。</p> <p>另一种<code>TypedArray</code>视图，与<code>DataView</code>视图的一个区别是，它不是一个构造函数，而是一组构造函数，代表不同的数据格式。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> x1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
x1<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> x2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
x2<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>  <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>

x1<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码对同一段内存，分别建立两种视图：32 位带符号整数（<code>Int32Array</code>构造函数）和 8 位不带符号整数（<code>Uint8Array</code>构造函数）。由于两个视图对应的是同一段内存，一个视图修改底层内存，会影响到另一个视图。</p> <p><code>TypedArray</code>视图的构造函数，除了接受<code>ArrayBuffer</code>实例作为参数，还可以接受普通数组作为参数，直接分配内存生成底层的<code>ArrayBuffer</code>实例，并同时完成对这段内存的赋值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> typedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
typedArray<span class="token punctuation">.</span>length <span class="token comment">// 3</span>

typedArray<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span>
typedArray <span class="token comment">// [5, 1, 2]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>上面代码使用<code>TypedArray</code>视图的<code>Uint8Array</code>构造函数，新建一个不带符号的 8 位整数视图。可以看到，<code>Uint8Array</code>直接使用普通数组作为参数，对底层内存的赋值同时完成。</p> <h3 id="arraybuffer-prototype-bytelength"><a href="#arraybuffer-prototype-bytelength" class="header-anchor">#</a> ArrayBuffer.prototype.byteLength</h3> <p><code>ArrayBuffer</code>实例的<code>byteLength</code>属性，返回所分配的内存区域的字节长度。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
buffer<span class="token punctuation">.</span>byteLength
<span class="token comment">// 32</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>如果要分配的内存区域很大，有可能分配失败（因为没有那么多的连续空余内存），所以有必要检查是否分配成功。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">if</span> <span class="token punctuation">(</span>buffer<span class="token punctuation">.</span>byteLength <span class="token operator">===</span> n<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 成功</span>
<span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
  <span class="token comment">// 失败</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h3 id="arraybuffer-prototype-slice"><a href="#arraybuffer-prototype-slice" class="header-anchor">#</a> ArrayBuffer.prototype.slice()</h3> <p><code>ArrayBuffer</code>实例有一个<code>slice</code>方法，允许将内存区域的一部分，拷贝生成一个新的<code>ArrayBuffer</code>对象。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> newBuffer <span class="token operator">=</span> buffer<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>上面代码拷贝<code>buffer</code>对象的前 3 个字节（从 0 开始，到第 3 个字节前面结束），生成一个新的<code>ArrayBuffer</code>对象。<code>slice</code>方法其实包含两步，第一步是先分配一段新内存，第二步是将原来那个<code>ArrayBuffer</code>对象拷贝过去。</p> <p><code>slice</code>方法接受两个参数，第一个参数表示拷贝开始的字节序号（含该字节），第二个参数表示拷贝截止的字节序号（不含该字节）。如果省略第二个参数，则默认到原<code>ArrayBuffer</code>对象的结尾。</p> <p>除了<code>slice</code>方法，<code>ArrayBuffer</code>对象不提供任何直接读写内存的方法，只允许在其上方建立视图，然后通过视图读写。</p> <h3 id="arraybuffer-isview"><a href="#arraybuffer-isview" class="header-anchor">#</a> ArrayBuffer.isView()</h3> <p><code>ArrayBuffer</code>有一个静态方法<code>isView</code>，返回一个布尔值，表示参数是否为<code>ArrayBuffer</code>的视图实例。这个方法大致相当于判断参数，是否为<code>TypedArray</code>实例或<code>DataView</code>实例。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
ArrayBuffer<span class="token punctuation">.</span><span class="token function">isView</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span> <span class="token comment">// false</span>

<span class="token keyword">const</span> v <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
ArrayBuffer<span class="token punctuation">.</span><span class="token function">isView</span><span class="token punctuation">(</span>v<span class="token punctuation">)</span> <span class="token comment">// true</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h2 id="typedarray-视图"><a href="#typedarray-视图" class="header-anchor">#</a> TypedArray 视图</h2> <h3 id="概述-2"><a href="#概述-2" class="header-anchor">#</a> 概述</h3> <p><code>ArrayBuffer</code>对象作为内存区域，可以存放多种类型的数据。同一段内存，不同数据有不同的解读方式，这就叫做“视图”（view）。<code>ArrayBuffer</code>有两种视图，一种是<code>TypedArray</code>视图，另一种是<code>DataView</code>视图。前者的数组成员都是同一个数据类型，后者的数组成员可以是不同的数据类型。</p> <p>目前，<code>TypedArray</code>视图一共包括 9 种类型，每一种视图都是一种构造函数。</p> <ul><li><strong><code>Int8Array</code></strong>：8 位有符号整数，长度 1 个字节。</li> <li><strong><code>Uint8Array</code></strong>：8 位无符号整数，长度 1 个字节。</li> <li><strong><code>Uint8ClampedArray</code></strong>：8 位无符号整数，长度 1 个字节，溢出处理不同。</li> <li><strong><code>Int16Array</code></strong>：16 位有符号整数，长度 2 个字节。</li> <li><strong><code>Uint16Array</code></strong>：16 位无符号整数，长度 2 个字节。</li> <li><strong><code>Int32Array</code></strong>：32 位有符号整数，长度 4 个字节。</li> <li><strong><code>Uint32Array</code></strong>：32 位无符号整数，长度 4 个字节。</li> <li><strong><code>Float32Array</code></strong>：32 位浮点数，长度 4 个字节。</li> <li><strong><code>Float64Array</code></strong>：64 位浮点数，长度 8 个字节。</li></ul> <p>这 9 个构造函数生成的数组，统称为<code>TypedArray</code>视图。它们很像普通数组，都有<code>length</code>属性，都能用方括号运算符（<code>[]</code>）获取单个元素，所有数组的方法，在它们上面都能使用。普通数组与 TypedArray 数组的差异主要在以下方面。</p> <ul><li>TypedArray 数组的所有成员，都是同一种类型。</li> <li>TypedArray 数组的成员是连续的，不会有空位。</li> <li>TypedArray 数组成员的默认值为 0。比如，<code>new Array(10)</code>返回一个普通数组，里面没有任何成员，只是 10 个空位；<code>new Uint8Array(10)</code>返回一个 TypedArray 数组，里面 10 个成员都是 0。</li> <li>TypedArray 数组只是一层视图，本身不储存数据，它的数据都储存在底层的<code>ArrayBuffer</code>对象之中，要获取底层对象必须使用<code>buffer</code>属性。</li></ul> <h3 id="构造函数"><a href="#构造函数" class="header-anchor">#</a> 构造函数</h3> <p>TypedArray 数组提供 9 种构造函数，用来生成相应类型的数组实例。</p> <p>构造函数有多种用法。</p> <p><strong>（1）TypedArray(buffer, byteOffset=0, length?)</strong></p> <p>同一个<code>ArrayBuffer</code>对象之上，可以根据不同的数据类型，建立多个视图。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 创建一个8字节的ArrayBuffer</span>
<span class="token keyword">const</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 创建一个指向b的Int32视图，开始于字节0，直到缓冲区的末尾</span>
<span class="token keyword">const</span> v1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 创建一个指向b的Uint8视图，开始于字节2，直到缓冲区的末尾</span>
<span class="token keyword">const</span> v2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 创建一个指向b的Int16视图，开始于字节2，长度为2</span>
<span class="token keyword">const</span> v3 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int16Array</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>上面代码在一段长度为 8 个字节的内存（<code>b</code>）之上，生成了三个视图：<code>v1</code>、<code>v2</code>和<code>v3</code>。</p> <p>视图的构造函数可以接受三个参数：</p> <ul><li>第一个参数（必需）：视图对应的底层<code>ArrayBuffer</code>对象。</li> <li>第二个参数（可选）：视图开始的字节序号，默认从 0 开始。</li> <li>第三个参数（可选）：视图包含的数据个数，默认直到本段内存区域结束。</li></ul> <p>因此，<code>v1</code>、<code>v2</code>和<code>v3</code>是重叠的：<code>v1[0]</code>是一个 32 位整数，指向字节 0 ～字节 3；<code>v2[0]</code>是一个 8 位无符号整数，指向字节 2；<code>v3[0]</code>是一个 16 位整数，指向字节 2 ～字节 3。只要任何一个视图对内存有所修改，就会在另外两个视图上反应出来。</p> <p>注意，<code>byteOffset</code>必须与所要建立的数据类型一致，否则会报错。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> i16 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int16Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// Uncaught RangeError: start offset of Int16Array should be a multiple of 2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>上面代码中，新生成一个 8 个字节的<code>ArrayBuffer</code>对象，然后在这个对象的第一个字节，建立带符号的 16 位整数视图，结果报错。因为，带符号的 16 位整数需要两个字节，所以<code>byteOffset</code>参数必须能够被 2 整除。</p> <p>如果想从任意字节开始解读<code>ArrayBuffer</code>对象，必须使用<code>DataView</code>视图，因为<code>TypedArray</code>视图只提供 9 种固定的解读格式。</p> <p><strong>（2）TypedArray(length)</strong></p> <p>视图还可以不通过<code>ArrayBuffer</code>对象，直接分配内存而生成。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> f64a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Float64Array</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
f64a<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">;</span>
f64a<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">20</span><span class="token punctuation">;</span>
f64a<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> f64a<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">+</span> f64a<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>上面代码生成一个 8 个成员的<code>Float64Array</code>数组（共 64 字节），然后依次对每个成员赋值。这时，视图构造函数的参数就是成员的个数。可以看到，视图数组的赋值操作与普通数组的操作毫无两样。</p> <p><strong>（3）TypedArray(typedArray)</strong></p> <p>TypedArray 数组的构造函数，可以接受另一个<code>TypedArray</code>实例作为参数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> typedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int8Array</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>上面代码中，<code>Int8Array</code>构造函数接受一个<code>Uint8Array</code>实例作为参数。</p> <p>注意，此时生成的新数组，只是复制了参数数组的值，对应的底层内存是不一样的。新数组会开辟一段新的内存储存数据，不会在原数组的内存之上建立视图。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> x <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int8Array</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> y <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int8Array</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
x<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 1</span>
y<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 1</span>

x<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
y<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 1</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>上面代码中，数组<code>y</code>是以数组<code>x</code>为模板而生成的，当<code>x</code>变动的时候，<code>y</code>并没有变动。</p> <p>如果想基于同一段内存，构造不同的视图，可以采用下面的写法。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> x <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int8Array</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> y <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int8Array</span><span class="token punctuation">(</span>x<span class="token punctuation">.</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
x<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 1</span>
y<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 1</span>

x<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
y<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p><strong>（4）TypedArray(arrayLikeObject)</strong></p> <p>构造函数的参数也可以是一个普通数组，然后直接生成<code>TypedArray</code>实例。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> typedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>注意，这时<code>TypedArray</code>视图会重新开辟内存，不会在原数组的内存上建立视图。</p> <p>上面代码从一个普通的数组，生成一个 8 位无符号整数的<code>TypedArray</code>实例。</p> <p>TypedArray 数组也可以转换回普通数组。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> normalArray <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token operator">...</span>typedArray<span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token comment">// or</span>
<span class="token keyword">const</span> normalArray <span class="token operator">=</span> Array<span class="token punctuation">.</span><span class="token function">from</span><span class="token punctuation">(</span>typedArray<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// or</span>
<span class="token keyword">const</span> normalArray <span class="token operator">=</span> <span class="token class-name">Array</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>typedArray<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h3 id="数组方法"><a href="#数组方法" class="header-anchor">#</a> 数组方法</h3> <p>普通数组的操作方法和属性，对 TypedArray 数组完全适用。</p> <ul><li><code>TypedArray.prototype.copyWithin(target, start[, end = this.length])</code></li> <li><code>TypedArray.prototype.entries()</code></li> <li><code>TypedArray.prototype.every(callbackfn, thisArg?)</code></li> <li><code>TypedArray.prototype.fill(value, start=0, end=this.length)</code></li> <li><code>TypedArray.prototype.filter(callbackfn, thisArg?)</code></li> <li><code>TypedArray.prototype.find(predicate, thisArg?)</code></li> <li><code>TypedArray.prototype.findIndex(predicate, thisArg?)</code></li> <li><code>TypedArray.prototype.forEach(callbackfn, thisArg?)</code></li> <li><code>TypedArray.prototype.indexOf(searchElement, fromIndex=0)</code></li> <li><code>TypedArray.prototype.join(separator)</code></li> <li><code>TypedArray.prototype.keys()</code></li> <li><code>TypedArray.prototype.lastIndexOf(searchElement, fromIndex?)</code></li> <li><code>TypedArray.prototype.map(callbackfn, thisArg?)</code></li> <li><code>TypedArray.prototype.reduce(callbackfn, initialValue?)</code></li> <li><code>TypedArray.prototype.reduceRight(callbackfn, initialValue?)</code></li> <li><code>TypedArray.prototype.reverse()</code></li> <li><code>TypedArray.prototype.slice(start=0, end=this.length)</code></li> <li><code>TypedArray.prototype.some(callbackfn, thisArg?)</code></li> <li><code>TypedArray.prototype.sort(comparefn)</code></li> <li><code>TypedArray.prototype.toLocaleString(reserved1?, reserved2?)</code></li> <li><code>TypedArray.prototype.toString()</code></li> <li><code>TypedArray.prototype.values()</code></li></ul> <p>上面所有方法的用法，请参阅数组方法的介绍，这里不再重复了。</p> <p>注意，TypedArray 数组没有<code>concat</code>方法。如果想要合并多个 TypedArray 数组，可以用下面这个函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">concatenate</span><span class="token punctuation">(</span><span class="token parameter">resultConstructor<span class="token punctuation">,</span> <span class="token operator">...</span>arrays</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> totalLength <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> arr <span class="token keyword">of</span> arrays<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    totalLength <span class="token operator">+=</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">let</span> result <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">resultConstructor</span><span class="token punctuation">(</span>totalLength<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> offset <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> arr <span class="token keyword">of</span> arrays<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    result<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> offset<span class="token punctuation">)</span><span class="token punctuation">;</span>
    offset <span class="token operator">+=</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token function">concatenate</span><span class="token punctuation">(</span>Uint8Array<span class="token punctuation">,</span> Uint8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span> Uint8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token comment">// Uint8Array [1, 2, 3, 4]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br></div></div><p>另外，TypedArray 数组与普通数组一样，部署了 Iterator 接口，所以可以被遍历。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">let</span> ui8 <span class="token operator">=</span> Uint8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> byte <span class="token keyword">of</span> ui8<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>byte<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">// 0</span>
<span class="token comment">// 1</span>
<span class="token comment">// 2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><h3 id="字节序"><a href="#字节序" class="header-anchor">#</a> 字节序</h3> <p>字节序指的是数值在内存中的表示方式。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> int32View <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> int32View<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  int32View<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> i <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>上面代码生成一个 16 字节的<code>ArrayBuffer</code>对象，然后在它的基础上，建立了一个 32 位整数的视图。由于每个 32 位整数占据 4 个字节，所以一共可以写入 4 个整数，依次为 0，2，4，6。</p> <p>如果在这段数据上接着建立一个 16 位整数的视图，则可以读出完全不一样的结果。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> int16View <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int16Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> int16View<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">&quot;Entry &quot;</span> <span class="token operator">+</span> i <span class="token operator">+</span> <span class="token string">&quot;: &quot;</span> <span class="token operator">+</span> int16View<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">// Entry 0: 0</span>
<span class="token comment">// Entry 1: 0</span>
<span class="token comment">// Entry 2: 2</span>
<span class="token comment">// Entry 3: 0</span>
<span class="token comment">// Entry 4: 4</span>
<span class="token comment">// Entry 5: 0</span>
<span class="token comment">// Entry 6: 6</span>
<span class="token comment">// Entry 7: 0</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>由于每个 16 位整数占据 2 个字节，所以整个<code>ArrayBuffer</code>对象现在分成 8 段。然后，由于 x86 体系的计算机都采用小端字节序（little endian），相对重要的字节排在后面的内存地址，相对不重要字节排在前面的内存地址，所以就得到了上面的结果。</p> <p>比如，一个占据四个字节的 16 进制数<code>0x12345678</code>，决定其大小的最重要的字节是“12”，最不重要的是“78”。小端字节序将最不重要的字节排在前面，储存顺序就是<code>78563412</code>；大端字节序则完全相反，将最重要的字节排在前面，储存顺序就是<code>12345678</code>。目前，所有个人电脑几乎都是小端字节序，所以 TypedArray 数组内部也采用小端字节序读写数据，或者更准确的说，按照本机操作系统设定的字节序读写数据。</p> <p>这并不意味大端字节序不重要，事实上，很多网络设备和特定的操作系统采用的是大端字节序。这就带来一个严重的问题：如果一段数据是大端字节序，TypedArray 数组将无法正确解析，因为它只能处理小端字节序！为了解决这个问题，JavaScript 引入<code>DataView</code>对象，可以设定字节序，下文会详细介绍。</p> <p>下面是另一个例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 假定某段buffer包含如下字节 [0x02, 0x01, 0x03, 0x07]</span>
<span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> v1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
v1<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
v1<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
v1<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
v1<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">7</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> uInt16View <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint16Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 计算机采用小端字节序</span>
<span class="token comment">// 所以头两个字节等于258</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>uInt16View<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">===</span> <span class="token number">258</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'OK'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// &quot;OK&quot;</span>
<span class="token punctuation">}</span>

<span class="token comment">// 赋值运算</span>
uInt16View<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">255</span><span class="token punctuation">;</span>    <span class="token comment">// 字节变为[0xFF, 0x00, 0x03, 0x07]</span>
uInt16View<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0xff05</span><span class="token punctuation">;</span> <span class="token comment">// 字节变为[0x05, 0xFF, 0x03, 0x07]</span>
uInt16View<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0x0210</span><span class="token punctuation">;</span> <span class="token comment">// 字节变为[0x05, 0xFF, 0x10, 0x02]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br></div></div><p>下面的函数可以用来判断，当前视图是小端字节序，还是大端字节序。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> <span class="token constant">BIG_ENDIAN</span> <span class="token operator">=</span> <span class="token function">Symbol</span><span class="token punctuation">(</span><span class="token string">'BIG_ENDIAN'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> <span class="token constant">LITTLE_ENDIAN</span> <span class="token operator">=</span> <span class="token function">Symbol</span><span class="token punctuation">(</span><span class="token string">'LITTLE_ENDIAN'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">function</span> <span class="token function">getPlatformEndianness</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> arr32 <span class="token operator">=</span> Uint32Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">0x12345678</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> arr8 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>arr32<span class="token punctuation">.</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">switch</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>arr8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token operator">*</span><span class="token number">0x1000000</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token punctuation">(</span>arr8<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token operator">*</span><span class="token number">0x10000</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token punctuation">(</span>arr8<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token operator">*</span><span class="token number">0x100</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token punctuation">(</span>arr8<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">case</span> <span class="token number">0x12345678</span><span class="token operator">:</span>
      <span class="token keyword">return</span> <span class="token constant">BIG_ENDIAN</span><span class="token punctuation">;</span>
    <span class="token keyword">case</span> <span class="token number">0x78563412</span><span class="token operator">:</span>
      <span class="token keyword">return</span> <span class="token constant">LITTLE_ENDIAN</span><span class="token punctuation">;</span>
    <span class="token keyword">default</span><span class="token operator">:</span>
      <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span><span class="token string">'Unknown endianness'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p>总之，与普通数组相比，TypedArray 数组的最大优点就是可以直接操作内存，不需要数据类型转换，所以速度快得多。</p> <h3 id="bytes-per-element-属性"><a href="#bytes-per-element-属性" class="header-anchor">#</a> BYTES_PER_ELEMENT 属性</h3> <p>每一种视图的构造函数，都有一个<code>BYTES_PER_ELEMENT</code>属性，表示这种数据类型占据的字节数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Int8Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 1</span>
Uint8Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 1</span>
Uint8ClampedArray<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 1</span>
Int16Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 2</span>
Uint16Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 2</span>
Int32Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 4</span>
Uint32Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 4</span>
Float32Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 4</span>
Float64Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token comment">// 8</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p>这个属性在<code>TypedArray</code>实例上也能获取，即有<code>TypedArray.prototype.BYTES_PER_ELEMENT</code>。</p> <h3 id="arraybuffer-与字符串的互相转换"><a href="#arraybuffer-与字符串的互相转换" class="header-anchor">#</a> ArrayBuffer 与字符串的互相转换</h3> <p><code>ArrayBuffer</code> 和字符串的相互转换，使用原生 <code>TextEncoder</code> 和 <code>TextDecoder</code> 方法。为了便于说明用法，下面的代码都按照 TypeScript 的用法，给出了类型签名。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">/**
 * Convert ArrayBuffer/TypedArray to String via TextDecoder
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
 */</span>
<span class="token keyword">function</span> <span class="token function">ab2str</span><span class="token punctuation">(</span>
  <span class="token literal-property property">input</span><span class="token operator">:</span> ArrayBuffer <span class="token operator">|</span> Uint8Array <span class="token operator">|</span> Int8Array <span class="token operator">|</span> Uint16Array <span class="token operator">|</span> Int16Array <span class="token operator">|</span> Uint32Array <span class="token operator">|</span> Int32Array<span class="token punctuation">,</span>
  <span class="token literal-property property">outputEncoding</span><span class="token operator">:</span> string <span class="token operator">=</span> <span class="token string">'utf8'</span><span class="token punctuation">,</span>
<span class="token punctuation">)</span><span class="token operator">:</span> string <span class="token punctuation">{</span>
  <span class="token keyword">const</span> decoder <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TextDecoder</span><span class="token punctuation">(</span>outputEncoding<span class="token punctuation">)</span>
  <span class="token keyword">return</span> decoder<span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span>input<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token comment">/**
 * Convert String to ArrayBuffer via TextEncoder
 *
 * @see https://developer.mozilla.org/zh-CN/docs/Web/API/TextEncoder
 */</span>
<span class="token keyword">function</span> <span class="token function">str2ab</span><span class="token punctuation">(</span><span class="token parameter"><span class="token literal-property property">input</span><span class="token operator">:</span> string</span><span class="token punctuation">)</span><span class="token operator">:</span> ArrayBuffer <span class="token punctuation">{</span>
  <span class="token keyword">const</span> view <span class="token operator">=</span> <span class="token function">str2Uint8Array</span><span class="token punctuation">(</span>input<span class="token punctuation">)</span>
  <span class="token keyword">return</span> view<span class="token punctuation">.</span>buffer
<span class="token punctuation">}</span>

<span class="token comment">/** Convert String to Uint8Array */</span>
<span class="token keyword">function</span> <span class="token function">str2Uint8Array</span><span class="token punctuation">(</span><span class="token parameter"><span class="token literal-property property">input</span><span class="token operator">:</span> string</span><span class="token punctuation">)</span><span class="token operator">:</span> Uint8Array <span class="token punctuation">{</span>
  <span class="token keyword">const</span> encoder <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TextEncoder</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">const</span> view <span class="token operator">=</span> encoder<span class="token punctuation">.</span><span class="token function">encode</span><span class="token punctuation">(</span>input<span class="token punctuation">)</span>
  <span class="token keyword">return</span> view
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br></div></div><p>上面代码中，<code>ab2str()</code>的第二个参数<code>outputEncoding</code>给出了输出编码的编码，一般保持默认值（<code>utf-8</code>），其他可选值参见<a href="https://encoding.spec.whatwg.org" target="_blank" rel="noopener noreferrer">官方文档<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>或 <a href="https://nodejs.org/api/util.html#util_whatwg_supported_encodings" target="_blank" rel="noopener noreferrer">Node.js 文档<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>。</p> <h3 id="溢出"><a href="#溢出" class="header-anchor">#</a> 溢出</h3> <p>不同的视图类型，所能容纳的数值范围是确定的。超出这个范围，就会出现溢出。比如，8 位视图只能容纳一个 8 位的二进制值，如果放入一个 9 位的值，就会溢出。</p> <p>TypedArray 数组的溢出处理规则，简单来说，就是抛弃溢出的位，然后按照视图类型进行解释。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> uint8 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

uint8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">256</span><span class="token punctuation">;</span>
uint8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 0</span>

uint8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
uint8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 255</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>上面代码中，<code>uint8</code>是一个 8 位视图，而 256 的二进制形式是一个 9 位的值<code>100000000</code>，这时就会发生溢出。根据规则，只会保留后 8 位，即<code>00000000</code>。<code>uint8</code>视图的解释规则是无符号的 8 位整数，所以<code>00000000</code>就是<code>0</code>。</p> <p>负数在计算机内部采用“2 的补码”表示，也就是说，将对应的正数值进行否运算，然后加<code>1</code>。比如，<code>-1</code>对应的正值是<code>1</code>，进行否运算以后，得到<code>11111110</code>，再加上<code>1</code>就是补码形式<code>11111111</code>。<code>uint8</code>按照无符号的 8 位整数解释<code>11111111</code>，返回结果就是<code>255</code>。</p> <p>一个简单转换规则，可以这样表示。</p> <ul><li>正向溢出（overflow）：当输入值大于当前数据类型的最大值，结果等于当前数据类型的最小值加上余值，再减去 1。</li> <li>负向溢出（underflow）：当输入值小于当前数据类型的最小值，结果等于当前数据类型的最大值减去余值的绝对值，再加上 1。</li></ul> <p>上面的“余值”就是模运算的结果，即 JavaScript 里面的<code>%</code>运算符的结果。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token number">12</span> <span class="token operator">%</span> <span class="token number">4</span> <span class="token comment">// 0</span>
<span class="token number">12</span> <span class="token operator">%</span> <span class="token number">5</span> <span class="token comment">// 2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>上面代码中，12 除以 4 是没有余值的，而除以 5 会得到余值 2。</p> <p>请看下面的例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> int8 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int8Array</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

int8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">128</span><span class="token punctuation">;</span>
int8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// -128</span>

int8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">129</span><span class="token punctuation">;</span>
int8<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 127</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>上面例子中，<code>int8</code>是一个带符号的 8 位整数视图，它的最大值是 127，最小值是-128。输入值为<code>128</code>时，相当于正向溢出<code>1</code>，根据“最小值加上余值（128 除以 127 的余值是 1），再减去 1”的规则，就会返回<code>-128</code>；输入值为<code>-129</code>时，相当于负向溢出<code>1</code>，根据“最大值减去余值的绝对值（-129 除以-128 的余值的绝对值是 1），再加上 1”的规则，就会返回<code>127</code>。</p> <p><code>Uint8ClampedArray</code>视图的溢出规则，与上面的规则不同。它规定，凡是发生正向溢出，该值一律等于当前数据类型的最大值，即 255；如果发生负向溢出，该值一律等于当前数据类型的最小值，即 0。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> uint8c <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8ClampedArray</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

uint8c<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">256</span><span class="token punctuation">;</span>
uint8c<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 255</span>

uint8c<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
uint8c<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token comment">// 0</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>上面例子中，<code>uint8C</code>是一个<code>Uint8ClampedArray</code>视图，正向溢出时都返回 255，负向溢出都返回 0。</p> <h3 id="typedarray-prototype-buffer"><a href="#typedarray-prototype-buffer" class="header-anchor">#</a> TypedArray.prototype.buffer</h3> <p><code>TypedArray</code>实例的<code>buffer</code>属性，返回整段内存区域对应的<code>ArrayBuffer</code>对象。该属性为只读属性。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Float32Array</span><span class="token punctuation">(</span><span class="token number">64</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>a<span class="token punctuation">.</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>上面代码的<code>a</code>视图对象和<code>b</code>视图对象，对应同一个<code>ArrayBuffer</code>对象，即同一段内存。</p> <h3 id="typedarray-prototype-bytelength-typedarray-prototype-byteoffset"><a href="#typedarray-prototype-bytelength-typedarray-prototype-byteoffset" class="header-anchor">#</a> TypedArray.prototype.byteLength，TypedArray.prototype.byteOffset</h3> <p><code>byteLength</code>属性返回 TypedArray 数组占据的内存长度，单位为字节。<code>byteOffset</code>属性返回 TypedArray 数组从底层<code>ArrayBuffer</code>对象的哪个字节开始。这两个属性都是只读属性。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> v1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> v2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> v3 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int16Array</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

v1<span class="token punctuation">.</span>byteLength <span class="token comment">// 8</span>
v2<span class="token punctuation">.</span>byteLength <span class="token comment">// 6</span>
v3<span class="token punctuation">.</span>byteLength <span class="token comment">// 4</span>

v1<span class="token punctuation">.</span>byteOffset <span class="token comment">// 0</span>
v2<span class="token punctuation">.</span>byteOffset <span class="token comment">// 2</span>
v3<span class="token punctuation">.</span>byteOffset <span class="token comment">// 2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><h3 id="typedarray-prototype-length"><a href="#typedarray-prototype-length" class="header-anchor">#</a> TypedArray.prototype.length</h3> <p><code>length</code>属性表示 <code>TypedArray</code> 数组含有多少个成员。注意将 <code>length</code> 属性和 <code>byteLength</code> 属性区分，前者是成员长度，后者是字节长度。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int16Array</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

a<span class="token punctuation">.</span>length <span class="token comment">// 8</span>
a<span class="token punctuation">.</span>byteLength <span class="token comment">// 16</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><h3 id="typedarray-prototype-set"><a href="#typedarray-prototype-set" class="header-anchor">#</a> TypedArray.prototype.set()</h3> <p>TypedArray 数组的<code>set</code>方法用于复制数组（普通数组或 TypedArray 数组），也就是将一段内容完全复制到另一段内存。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

b<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>上面代码复制<code>a</code>数组的内容到<code>b</code>数组，它是整段内存的复制，比一个个拷贝成员的那种复制快得多。</p> <p><code>set</code>方法还可以接受第二个参数，表示从<code>b</code>对象的哪一个成员开始复制<code>a</code>对象。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint16Array</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint16Array</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

b<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>a<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>上面代码的<code>b</code>数组比<code>a</code>数组多两个成员，所以从<code>b[2]</code>开始复制。</p> <h3 id="typedarray-prototype-subarray"><a href="#typedarray-prototype-subarray" class="header-anchor">#</a> TypedArray.prototype.subarray()</h3> <p><code>subarray</code>方法是对于 TypedArray 数组的一部分，再建立一个新的视图。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint16Array</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> b <span class="token operator">=</span> a<span class="token punctuation">.</span><span class="token function">subarray</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

a<span class="token punctuation">.</span>byteLength <span class="token comment">// 16</span>
b<span class="token punctuation">.</span>byteLength <span class="token comment">// 2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p><code>subarray</code>方法的第一个参数是起始的成员序号，第二个参数是结束的成员序号（不含该成员），如果省略则包含剩余的全部成员。所以，上面代码的<code>a.subarray(2,3)</code>，意味着 b 只包含<code>a[2]</code>一个成员，字节长度为 2。</p> <h3 id="typedarray-prototype-slice"><a href="#typedarray-prototype-slice" class="header-anchor">#</a> TypedArray.prototype.slice()</h3> <p>TypeArray 实例的<code>slice</code>方法，可以返回一个指定位置的新的<code>TypedArray</code>实例。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">let</span> ui8 <span class="token operator">=</span> Uint8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
ui8<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token comment">// Uint8Array [ 2 ]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>上面代码中，<code>ui8</code>是 8 位无符号整数数组视图的一个实例。它的<code>slice</code>方法可以从当前视图之中，返回一个新的视图实例。</p> <p><code>slice</code>方法的参数，表示原数组的具体位置，开始生成新数组。负值表示逆向的位置，即-1 为倒数第一个位置，-2 表示倒数第二个位置，以此类推。</p> <h3 id="typedarray-of"><a href="#typedarray-of" class="header-anchor">#</a> TypedArray.of()</h3> <p>TypedArray 数组的所有构造函数，都有一个静态方法<code>of</code>，用于将参数转为一个<code>TypedArray</code>实例。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Float32Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">0.151</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">3.7</span><span class="token punctuation">)</span>
<span class="token comment">// Float32Array [ 0.151, -8, 3.7 ]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>下面三种方法都会生成同样一个 TypedArray 数组。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 方法一</span>
<span class="token keyword">let</span> tarr <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 方法二</span>
<span class="token keyword">let</span> tarr <span class="token operator">=</span> Uint8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 方法三</span>
<span class="token keyword">let</span> tarr <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
tarr<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
tarr<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
tarr<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><h3 id="typedarray-from"><a href="#typedarray-from" class="header-anchor">#</a> TypedArray.from()</h3> <p>静态方法<code>from</code>接受一个可遍历的数据结构（比如数组）作为参数，返回一个基于这个结构的<code>TypedArray</code>实例。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Uint16Array<span class="token punctuation">.</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token comment">// Uint16Array [ 0, 1, 2 ]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>这个方法还可以将一种<code>TypedArray</code>实例，转为另一种。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> ui16 <span class="token operator">=</span> Uint16Array<span class="token punctuation">.</span><span class="token function">from</span><span class="token punctuation">(</span>Uint8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
ui16 <span class="token keyword">instanceof</span> <span class="token class-name">Uint16Array</span> <span class="token comment">// true</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><code>from</code>方法还可以接受一个函数，作为第二个参数，用来对每个元素进行遍历，功能类似<code>map</code>方法。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Int8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">127</span><span class="token punctuation">,</span> <span class="token number">126</span><span class="token punctuation">,</span> <span class="token number">125</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token parameter">x</span> <span class="token operator">=&gt;</span> <span class="token number">2</span> <span class="token operator">*</span> x<span class="token punctuation">)</span>
<span class="token comment">// Int8Array [ -2, -4, -6 ]</span>

Int16Array<span class="token punctuation">.</span><span class="token function">from</span><span class="token punctuation">(</span>Int8Array<span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">127</span><span class="token punctuation">,</span> <span class="token number">126</span><span class="token punctuation">,</span> <span class="token number">125</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token parameter">x</span> <span class="token operator">=&gt;</span> <span class="token number">2</span> <span class="token operator">*</span> x<span class="token punctuation">)</span>
<span class="token comment">// Int16Array [ 254, 252, 250 ]</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>上面的例子中，<code>from</code>方法没有发生溢出，这说明遍历不是针对原来的 8 位整数数组。也就是说，<code>from</code>会将第一个参数指定的 TypedArray 数组，拷贝到另一段内存之中，处理之后再将结果转成指定的数组格式。</p> <h2 id="复合视图"><a href="#复合视图" class="header-anchor">#</a> 复合视图</h2> <p>由于视图的构造函数可以指定起始位置和长度，所以在同一段内存之中，可以依次存放不同类型的数据，这叫做“复合视图”。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">24</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> idView <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint32Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> usernameView <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> amountDueView <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Float32Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>上面代码将一个 24 字节长度的<code>ArrayBuffer</code>对象，分成三个部分：</p> <ul><li>字节 0 到字节 3：1 个 32 位无符号整数</li> <li>字节 4 到字节 19：16 个 8 位整数</li> <li>字节 20 到字节 23：1 个 32 位浮点数</li></ul> <p>这种数据结构可以用如下的 C 语言描述：</p> <div class="language-c line-numbers-mode"><pre class="language-c"><code><span class="token keyword">struct</span> <span class="token class-name">someStruct</span> <span class="token punctuation">{</span>
  <span class="token keyword">unsigned</span> <span class="token keyword">long</span> id<span class="token punctuation">;</span>
  <span class="token keyword">char</span> username<span class="token punctuation">[</span><span class="token number">16</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token keyword">float</span> amountDue<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h2 id="dataview-视图"><a href="#dataview-视图" class="header-anchor">#</a> DataView 视图</h2> <p>如果一段数据包括多种类型（比如服务器传来的 HTTP 数据），这时除了建立<code>ArrayBuffer</code>对象的复合视图以外，还可以通过<code>DataView</code>视图进行操作。</p> <p><code>DataView</code>视图提供更多操作选项，而且支持设定字节序。本来，在设计目的上，<code>ArrayBuffer</code>对象的各种<code>TypedArray</code>视图，是用来向网卡、声卡之类的本机设备传送数据，所以使用本机的字节序就可以了；而<code>DataView</code>视图的设计目的，是用来处理网络设备传来的数据，所以大端字节序或小端字节序是可以自行设定的。</p> <p><code>DataView</code>视图本身也是构造函数，接受一个<code>ArrayBuffer</code>对象作为参数，生成视图。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token function">DataView</span><span class="token punctuation">(</span>ArrayBuffer buffer <span class="token punctuation">[</span><span class="token punctuation">,</span> 字节起始位置 <span class="token punctuation">[</span><span class="token punctuation">,</span> 长度<span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>下面是一个例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">24</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> dv <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DataView</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><code>DataView</code>实例有以下属性，含义与<code>TypedArray</code>实例的同名方法相同。</p> <ul><li><code>DataView.prototype.buffer</code>：返回对应的 ArrayBuffer 对象</li> <li><code>DataView.prototype.byteLength</code>：返回占据的内存字节长度</li> <li><code>DataView.prototype.byteOffset</code>：返回当前视图从对应的 ArrayBuffer 对象的哪个字节开始</li></ul> <p><code>DataView</code>实例提供 8 个方法读取内存。</p> <ul><li><strong><code>getInt8</code></strong>：读取 1 个字节，返回一个 8 位整数。</li> <li><strong><code>getUint8</code></strong>：读取 1 个字节，返回一个无符号的 8 位整数。</li> <li><strong><code>getInt16</code></strong>：读取 2 个字节，返回一个 16 位整数。</li> <li><strong><code>getUint16</code></strong>：读取 2 个字节，返回一个无符号的 16 位整数。</li> <li><strong><code>getInt32</code></strong>：读取 4 个字节，返回一个 32 位整数。</li> <li><strong><code>getUint32</code></strong>：读取 4 个字节，返回一个无符号的 32 位整数。</li> <li><strong><code>getFloat32</code></strong>：读取 4 个字节，返回一个 32 位浮点数。</li> <li><strong><code>getFloat64</code></strong>：读取 8 个字节，返回一个 64 位浮点数。</li></ul> <p>这一系列<code>get</code>方法的参数都是一个字节序号（不能是负数，否则会报错），表示从哪个字节开始读取。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">24</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> dv <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DataView</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 从第1个字节读取一个8位无符号整数</span>
<span class="token keyword">const</span> v1 <span class="token operator">=</span> dv<span class="token punctuation">.</span><span class="token function">getUint8</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 从第2个字节读取一个16位无符号整数</span>
<span class="token keyword">const</span> v2 <span class="token operator">=</span> dv<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 从第4个字节读取一个16位无符号整数</span>
<span class="token keyword">const</span> v3 <span class="token operator">=</span> dv<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>上面代码读取了<code>ArrayBuffer</code>对象的前 5 个字节，其中有一个 8 位整数和两个十六位整数。</p> <p>如果一次读取两个或两个以上字节，就必须明确数据的存储方式，到底是小端字节序还是大端字节序。默认情况下，<code>DataView</code>的<code>get</code>方法使用大端字节序解读数据，如果需要使用小端字节序解读，必须在<code>get</code>方法的第二个参数指定<code>true</code>。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 小端字节序</span>
<span class="token keyword">const</span> v1 <span class="token operator">=</span> dv<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 大端字节序</span>
<span class="token keyword">const</span> v2 <span class="token operator">=</span> dv<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 大端字节序</span>
<span class="token keyword">const</span> v3 <span class="token operator">=</span> dv<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>DataView 视图提供 8 个方法写入内存。</p> <ul><li><strong><code>setInt8</code></strong>：写入 1 个字节的 8 位整数。</li> <li><strong><code>setUint8</code></strong>：写入 1 个字节的 8 位无符号整数。</li> <li><strong><code>setInt16</code></strong>：写入 2 个字节的 16 位整数。</li> <li><strong><code>setUint16</code></strong>：写入 2 个字节的 16 位无符号整数。</li> <li><strong><code>setInt32</code></strong>：写入 4 个字节的 32 位整数。</li> <li><strong><code>setUint32</code></strong>：写入 4 个字节的 32 位无符号整数。</li> <li><strong><code>setFloat32</code></strong>：写入 4 个字节的 32 位浮点数。</li> <li><strong><code>setFloat64</code></strong>：写入 8 个字节的 64 位浮点数。</li></ul> <p>这一系列<code>set</code>方法，接受两个参数，第一个参数是字节序号，表示从哪个字节开始写入，第二个参数为写入的数据。对于那些写入两个或两个以上字节的方法，需要指定第三个参数，<code>false</code>或者<code>undefined</code>表示使用大端字节序写入，<code>true</code>表示使用小端字节序写入。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 在第1个字节，以大端字节序写入值为25的32位整数</span>
dv<span class="token punctuation">.</span><span class="token function">setInt32</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">25</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 在第5个字节，以大端字节序写入值为25的32位整数</span>
dv<span class="token punctuation">.</span><span class="token function">setInt32</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">25</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 在第9个字节，以小端字节序写入值为2.5的32位浮点数</span>
dv<span class="token punctuation">.</span><span class="token function">setFloat32</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">2.5</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>如果不确定正在使用的计算机的字节序，可以采用下面的判断方式。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> littleEndian <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> buffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBuffer</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">new</span> <span class="token class-name">DataView</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setInt16</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">256</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Int16Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">===</span> <span class="token number">256</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>如果返回<code>true</code>，就是小端字节序；如果返回<code>false</code>，就是大端字节序。</p> <h2 id="二进制数组的应用"><a href="#二进制数组的应用" class="header-anchor">#</a> 二进制数组的应用</h2> <p>大量的 Web API 用到了<code>ArrayBuffer</code>对象和它的视图对象。</p> <h3 id="ajax"><a href="#ajax" class="header-anchor">#</a> AJAX</h3> <p>传统上，服务器通过 AJAX 操作只能返回文本数据，即<code>responseType</code>属性默认为<code>text</code>。<code>XMLHttpRequest</code>第二版<code>XHR2</code>允许服务器返回二进制数据，这时分成两种情况。如果明确知道返回的二进制数据类型，可以把返回类型（<code>responseType</code>）设为<code>arraybuffer</code>；如果不知道，就设为<code>blob</code>。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">let</span> xhr <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">XMLHttpRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
xhr<span class="token punctuation">.</span><span class="token function">open</span><span class="token punctuation">(</span><span class="token string">'GET'</span><span class="token punctuation">,</span> someUrl<span class="token punctuation">)</span><span class="token punctuation">;</span>
xhr<span class="token punctuation">.</span>responseType <span class="token operator">=</span> <span class="token string">'arraybuffer'</span><span class="token punctuation">;</span>

xhr<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> arrayBuffer <span class="token operator">=</span> xhr<span class="token punctuation">.</span>response<span class="token punctuation">;</span>
  <span class="token comment">// ···</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

xhr<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>如果知道传回来的是 32 位整数，可以像下面这样处理。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>xhr<span class="token punctuation">.</span><span class="token function-variable function">onreadystatechange</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>req<span class="token punctuation">.</span>readyState <span class="token operator">===</span> <span class="token number">4</span> <span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> arrayResponse <span class="token operator">=</span> xhr<span class="token punctuation">.</span>response<span class="token punctuation">;</span>
    <span class="token keyword">const</span> dataView <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DataView</span><span class="token punctuation">(</span>arrayResponse<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> ints <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint32Array</span><span class="token punctuation">(</span>dataView<span class="token punctuation">.</span>byteLength <span class="token operator">/</span> <span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    xhrDiv<span class="token punctuation">.</span>style<span class="token punctuation">.</span>backgroundColor <span class="token operator">=</span> <span class="token string">&quot;#00FF00&quot;</span><span class="token punctuation">;</span>
    xhrDiv<span class="token punctuation">.</span>innerText <span class="token operator">=</span> <span class="token string">&quot;Array is &quot;</span> <span class="token operator">+</span> ints<span class="token punctuation">.</span>length <span class="token operator">+</span> <span class="token string">&quot;uints long&quot;</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><h3 id="canvas"><a href="#canvas" class="header-anchor">#</a> Canvas</h3> <p>网页<code>Canvas</code>元素输出的二进制像素数据，就是 TypedArray 数组。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> canvas <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'myCanvas'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> ctx <span class="token operator">=</span> canvas<span class="token punctuation">.</span><span class="token function">getContext</span><span class="token punctuation">(</span><span class="token string">'2d'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> imageData <span class="token operator">=</span> ctx<span class="token punctuation">.</span><span class="token function">getImageData</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> canvas<span class="token punctuation">.</span>width<span class="token punctuation">,</span> canvas<span class="token punctuation">.</span>height<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> uint8ClampedArray <span class="token operator">=</span> imageData<span class="token punctuation">.</span>data<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>需要注意的是，上面代码的<code>uint8ClampedArray</code>虽然是一个 TypedArray 数组，但是它的视图类型是一种针对<code>Canvas</code>元素的专有类型<code>Uint8ClampedArray</code>。这个视图类型的特点，就是专门针对颜色，把每个字节解读为无符号的 8 位整数，即只能取值 0 ～ 255，而且发生运算的时候自动过滤高位溢出。这为图像处理带来了巨大的方便。</p> <p>举例来说，如果把像素的颜色值设为<code>Uint8Array</code>类型，那么乘以一个 gamma 值的时候，就必须这样计算：</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>u8<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">,</span> Math<span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> u8<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">*</span> gamma<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>因为<code>Uint8Array</code>类型对于大于 255 的运算结果（比如<code>0xFF+1</code>），会自动变为<code>0x00</code>，所以图像处理必须要像上面这样算。这样做很麻烦，而且影响性能。如果将颜色值设为<code>Uint8ClampedArray</code>类型，计算就简化许多。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>pixels<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">*=</span> gamma<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>Uint8ClampedArray</code>类型确保将小于 0 的值设为 0，将大于 255 的值设为 255。注意，IE 10 不支持该类型。</p> <h3 id="websocket"><a href="#websocket" class="header-anchor">#</a> WebSocket</h3> <p><code>WebSocket</code>可以通过<code>ArrayBuffer</code>，发送或接收二进制数据。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">let</span> socket <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">WebSocket</span><span class="token punctuation">(</span><span class="token string">'ws://127.0.0.1:8081'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
socket<span class="token punctuation">.</span>binaryType <span class="token operator">=</span> <span class="token string">'arraybuffer'</span><span class="token punctuation">;</span>

<span class="token comment">// Wait until socket is open</span>
socket<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'open'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">event</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// Send binary data</span>
  <span class="token keyword">const</span> typedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  socket<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span>typedArray<span class="token punctuation">.</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// Receive binary data</span>
socket<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">event</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> arrayBuffer <span class="token operator">=</span> event<span class="token punctuation">.</span>data<span class="token punctuation">;</span>
  <span class="token comment">// ···</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><h3 id="fetch-api"><a href="#fetch-api" class="header-anchor">#</a> Fetch API</h3> <p>Fetch API 取回的数据，就是<code>ArrayBuffer</code>对象。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token function">fetch</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">response</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">return</span> response<span class="token punctuation">.</span><span class="token function">arrayBuffer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">arrayBuffer</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// ...</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><h3 id="file-api"><a href="#file-api" class="header-anchor">#</a> File API</h3> <p>如果知道一个文件的二进制数据类型，也可以将这个文件读取为<code>ArrayBuffer</code>对象。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> fileInput <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'fileInput'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> file <span class="token operator">=</span> fileInput<span class="token punctuation">.</span>files<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> reader <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileReader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
reader<span class="token punctuation">.</span><span class="token function">readAsArrayBuffer</span><span class="token punctuation">(</span>file<span class="token punctuation">)</span><span class="token punctuation">;</span>
reader<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> arrayBuffer <span class="token operator">=</span> reader<span class="token punctuation">.</span>result<span class="token punctuation">;</span>
  <span class="token comment">// ···</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>下面以处理 bmp 文件为例。假定<code>file</code>变量是一个指向 bmp 文件的文件对象，首先读取文件。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> reader <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileReader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
reader<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">&quot;load&quot;</span><span class="token punctuation">,</span> processimage<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
reader<span class="token punctuation">.</span><span class="token function">readAsArrayBuffer</span><span class="token punctuation">(</span>file<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>然后，定义处理图像的回调函数：先在二进制数据之上建立一个<code>DataView</code>视图，再建立一个<code>bitmap</code>对象，用于存放处理后的数据，最后将图像展示在<code>Canvas</code>元素之中。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">processimage</span><span class="token punctuation">(</span><span class="token parameter">e</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> buffer <span class="token operator">=</span> e<span class="token punctuation">.</span>target<span class="token punctuation">.</span>result<span class="token punctuation">;</span>
  <span class="token keyword">const</span> datav <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DataView</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> bitmap <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token comment">// 具体的处理步骤</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>具体处理图像数据时，先处理 bmp 的文件头。具体每个文件头的格式和定义，请参阅有关资料。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>bitmap<span class="token punctuation">.</span>fileheader <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>fileheader<span class="token punctuation">.</span>bfType <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>fileheader<span class="token punctuation">.</span>bfSize <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>fileheader<span class="token punctuation">.</span>bfReserved1 <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>fileheader<span class="token punctuation">.</span>bfReserved2 <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>fileheader<span class="token punctuation">.</span>bfOffBits <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>接着处理图像元信息部分。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>bitmap<span class="token punctuation">.</span>infoheader <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biSize <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">14</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biWidth <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">18</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biHeight <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">22</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biPlanes <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">26</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biBitCount <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint16</span><span class="token punctuation">(</span><span class="token number">28</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biCompression <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biSizeImage <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">34</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biXPelsPerMeter <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">38</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biYPelsPerMeter <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">42</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biClrUsed <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">46</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>infoheader<span class="token punctuation">.</span>biClrImportant <span class="token operator">=</span> datav<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span><span class="token number">50</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>最后处理图像本身的像素信息。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> start <span class="token operator">=</span> bitmap<span class="token punctuation">.</span>fileheader<span class="token punctuation">.</span>bfOffBits<span class="token punctuation">;</span>
bitmap<span class="token punctuation">.</span>pixels <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span>buffer<span class="token punctuation">,</span> start<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>至此，图像文件的数据全部处理完成。下一步，可以根据需要，进行图像变形，或者转换格式，或者展示在<code>Canvas</code>网页元素之中。</p> <h2 id="sharedarraybuffer"><a href="#sharedarraybuffer" class="header-anchor">#</a> SharedArrayBuffer</h2> <p>JavaScript 是单线程的，Web worker 引入了多线程：主线程用来与用户互动，Worker 线程用来承担计算任务。每个线程的数据都是隔离的，通过<code>postMessage()</code>通信。下面是一个例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>
<span class="token keyword">const</span> w <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Worker</span><span class="token punctuation">(</span><span class="token string">'myworker.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>上面代码中，主线程新建了一个 Worker 线程。该线程与主线程之间会有一个通信渠道，主线程通过<code>w.postMessage</code>向 Worker 线程发消息，同时通过<code>message</code>事件监听 Worker 线程的回应。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>
w<span class="token punctuation">.</span><span class="token function">postMessage</span><span class="token punctuation">(</span><span class="token string">'hi'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
w<span class="token punctuation">.</span><span class="token function-variable function">onmessage</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">ev</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ev<span class="token punctuation">.</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>上面代码中，主线程先发一个消息<code>hi</code>，然后在监听到 Worker 线程的回应后，就将其打印出来。</p> <p>Worker 线程也是通过监听<code>message</code>事件，来获取主线程发来的消息，并作出反应。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// Worker 线程</span>
<span class="token function-variable function">onmessage</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">ev</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ev<span class="token punctuation">.</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token function">postMessage</span><span class="token punctuation">(</span><span class="token string">'ho'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>线程之间的数据交换可以是各种格式，不仅仅是字符串，也可以是二进制数据。这种交换采用的是复制机制，即一个进程将需要分享的数据复制一份，通过<code>postMessage</code>方法交给另一个进程。如果数据量比较大，这种通信的效率显然比较低。很容易想到，这时可以留出一块内存区域，由主线程与 Worker 线程共享，两方都可以读写，那么就会大大提高效率，协作起来也会比较简单（不像<code>postMessage</code>那么麻烦）。</p> <p>ES2017 引入<a href="https://github.com/tc39/ecmascript_sharedmem/blob/master/TUTORIAL.md" target="_blank" rel="noopener noreferrer"><code>SharedArrayBuffer</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>，允许 Worker 线程与主线程共享同一块内存。<code>SharedArrayBuffer</code>的 API 与<code>ArrayBuffer</code>一模一样，唯一的区别是后者无法共享数据。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>

<span class="token comment">// 新建 1KB 共享内存</span>
<span class="token keyword">const</span> sharedBuffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SharedArrayBuffer</span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 主线程将共享内存的地址发送出去</span>
w<span class="token punctuation">.</span><span class="token function">postMessage</span><span class="token punctuation">(</span>sharedBuffer<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 在共享内存上建立视图，供写入数据</span>
<span class="token keyword">const</span> sharedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>sharedBuffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>上面代码中，<code>postMessage</code>方法的参数是<code>SharedArrayBuffer</code>对象。</p> <p>Worker 线程从事件的<code>data</code>属性上面取到数据。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// Worker 线程</span>
<span class="token function-variable function">onmessage</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">ev</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 主线程共享的数据，就是 1KB 的共享内存</span>
  <span class="token keyword">const</span> sharedBuffer <span class="token operator">=</span> ev<span class="token punctuation">.</span>data<span class="token punctuation">;</span>

  <span class="token comment">// 在共享内存上建立视图，方便读写</span>
  <span class="token keyword">const</span> sharedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>sharedBuffer<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// ...</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>共享内存也可以在 Worker 线程创建，发给主线程。</p> <p><code>SharedArrayBuffer</code>与<code>ArrayBuffer</code>一样，本身是无法读写的，必须在上面建立视图，然后通过视图读写。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 分配 10 万个 32 位整数占据的内存空间</span>
<span class="token keyword">const</span> sab <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SharedArrayBuffer</span><span class="token punctuation">(</span>Int32Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token operator">*</span> <span class="token number">100000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 建立 32 位整数视图</span>
<span class="token keyword">const</span> ia <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>sab<span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// ia.length == 100000</span>

<span class="token comment">// 新建一个质数生成器</span>
<span class="token keyword">const</span> primes <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PrimeGenerator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 将 10 万个质数，写入这段内存空间</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span> <span class="token keyword">let</span> i<span class="token operator">=</span><span class="token number">0</span> <span class="token punctuation">;</span> i <span class="token operator">&lt;</span> ia<span class="token punctuation">.</span>length <span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">)</span>
  ia<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> primes<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 向 Worker 线程发送这段共享内存</span>
w<span class="token punctuation">.</span><span class="token function">postMessage</span><span class="token punctuation">(</span>ia<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p>Worker 线程收到数据后的处理如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// Worker 线程</span>
<span class="token keyword">let</span> ia<span class="token punctuation">;</span>
<span class="token function-variable function">onmessage</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">ev</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  ia <span class="token operator">=</span> ev<span class="token punctuation">.</span>data<span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 100000</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">[</span><span class="token number">37</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 输出 163，因为这是第38个质数</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><h2 id="atomics-对象"><a href="#atomics-对象" class="header-anchor">#</a> Atomics 对象</h2> <p>多线程共享内存，最大的问题就是如何防止两个线程同时修改某个地址，或者说，当一个线程修改共享内存以后，必须有一个机制让其他线程同步。SharedArrayBuffer API 提供<code>Atomics</code>对象，保证所有共享内存的操作都是“原子性”的，并且可以在所有线程内同步。</p> <p>什么叫“原子性操作”呢？现代编程语言中，一条普通的命令被编译器处理以后，会变成多条机器指令。如果是单线程运行，这是没有问题的；多线程环境并且共享内存时，就会出问题，因为这一组机器指令的运行期间，可能会插入其他线程的指令，从而导致运行结果出错。请看下面的例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>
ia<span class="token punctuation">[</span><span class="token number">42</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">314159</span><span class="token punctuation">;</span>  <span class="token comment">// 原先的值 191</span>
ia<span class="token punctuation">[</span><span class="token number">37</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">123456</span><span class="token punctuation">;</span>  <span class="token comment">// 原先的值 163</span>

<span class="token comment">// Worker 线程</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">[</span><span class="token number">37</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">[</span><span class="token number">42</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 可能的结果</span>
<span class="token comment">// 123456</span>
<span class="token comment">// 191</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>上面代码中，主线程的原始顺序是先对 42 号位置赋值，再对 37 号位置赋值。但是，编译器和 CPU 为了优化，可能会改变这两个操作的执行顺序（因为它们之间互不依赖），先对 37 号位置赋值，再对 42 号位置赋值。而执行到一半的时候，Worker 线程可能就会来读取数据，导致打印出<code>123456</code>和<code>191</code>。</p> <p>下面是另一个例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>
<span class="token keyword">const</span> sab <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SharedArrayBuffer</span><span class="token punctuation">(</span>Int32Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token operator">*</span> <span class="token number">100000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> ia <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>sab<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> ia<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  ia<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> primes<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 将质数放入 ia</span>
<span class="token punctuation">}</span>

<span class="token comment">// worker 线程</span>
ia<span class="token punctuation">[</span><span class="token number">112</span><span class="token punctuation">]</span><span class="token operator">++</span><span class="token punctuation">;</span> <span class="token comment">// 错误</span>
Atomics<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>ia<span class="token punctuation">,</span> <span class="token number">112</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 正确</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>上面代码中，Worker 线程直接改写共享内存<code>ia[112]++</code>是不正确的。因为这行语句会被编译成多条机器指令，这些指令之间无法保证不会插入其他进程的指令。请设想如果两个线程同时<code>ia[112]++</code>，很可能它们得到的结果都是不正确的。</p> <p><code>Atomics</code>对象就是为了解决这个问题而提出，它可以保证一个操作所对应的多条机器指令，一定是作为一个整体运行的，中间不会被打断。也就是说，它所涉及的操作都可以看作是原子性的单操作，这可以避免线程竞争，提高多线程共享内存时的操作安全。所以，<code>ia[112]++</code>要改写成<code>Atomics.add(ia, 112, 1)</code>。</p> <p><code>Atomics</code>对象提供多种方法。</p> <p><strong>（1）Atomics.store()，Atomics.load()</strong></p> <p><code>store()</code>方法用来向共享内存写入数据，<code>load()</code>方法用来从共享内存读出数据。比起直接的读写操作，它们的好处是保证了读写操作的原子性。</p> <p>此外，它们还用来解决一个问题：多个线程使用共享内存的某个位置作为开关（flag），一旦该位置的值变了，就执行特定操作。这时，必须保证该位置的赋值操作，一定是在它前面的所有可能会改写内存的操作结束后执行；而该位置的取值操作，一定是在它后面所有可能会读取该位置的操作开始之前执行。<code>store</code>方法和<code>load</code>方法就能做到这一点，编译器不会为了优化，而打乱机器指令的执行顺序。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> index<span class="token punctuation">)</span>
Atomics<span class="token punctuation">.</span><span class="token function">store</span><span class="token punctuation">(</span>array<span class="token punctuation">,</span> index<span class="token punctuation">,</span> value<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><code>store</code>方法接受三个参数：SharedBuffer 的视图、位置索引和值，返回<code>sharedArray[index]</code>的值。<code>load</code>方法只接受两个参数：SharedBuffer 的视图和位置索引，也是返回<code>sharedArray[index]</code>的值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程 main.js</span>
ia<span class="token punctuation">[</span><span class="token number">42</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">314159</span><span class="token punctuation">;</span>  <span class="token comment">// 原先的值 191</span>
Atomics<span class="token punctuation">.</span><span class="token function">store</span><span class="token punctuation">(</span>ia<span class="token punctuation">,</span> <span class="token number">37</span><span class="token punctuation">,</span> <span class="token number">123456</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// 原先的值是 163</span>

<span class="token comment">// Worker 线程 worker.js</span>
<span class="token keyword">while</span> <span class="token punctuation">(</span>Atomics<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>ia<span class="token punctuation">,</span> <span class="token number">37</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">163</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">[</span><span class="token number">37</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// 123456</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">[</span><span class="token number">42</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// 314159</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码中，主线程的<code>Atomics.store</code>向 42 号位置的赋值，一定是早于 37 位置的赋值。只要 37 号位置等于 163，Worker 线程就不会终止循环，而对 37 号位置和 42 号位置的取值，一定是在<code>Atomics.load</code>操作之后。</p> <p>下面是另一个例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>
<span class="token keyword">const</span> worker <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Worker</span><span class="token punctuation">(</span><span class="token string">'worker.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> length <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> size <span class="token operator">=</span> Int32Array<span class="token punctuation">.</span><span class="token constant">BYTES_PER_ELEMENT</span> <span class="token operator">*</span> length<span class="token punctuation">;</span>
<span class="token comment">// 新建一段共享内存</span>
<span class="token keyword">const</span> sharedBuffer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SharedArrayBuffer</span><span class="token punctuation">(</span>size<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> sharedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>sharedBuffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 向共享内存写入 10 个整数</span>
  Atomics<span class="token punctuation">.</span><span class="token function">store</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> i<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
worker<span class="token punctuation">.</span><span class="token function">postMessage</span><span class="token punctuation">(</span>sharedBuffer<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>上面代码中，主线程用<code>Atomics.store()</code>方法写入数据。下面是 Worker 线程用<code>Atomics.load()</code>方法读取数据。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// worker.js</span>
self<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">event</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> sharedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>event<span class="token punctuation">.</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> arrayValue <span class="token operator">=</span> Atomics<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">The item at array index </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>i<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> is </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>arrayValue<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p><strong>（2）Atomics.exchange()</strong></p> <p>Worker 线程如果要写入数据，可以使用上面的<code>Atomics.store()</code>方法，也可以使用<code>Atomics.exchange()</code>方法。它们的区别是，<code>Atomics.store()</code>返回写入的值，而<code>Atomics.exchange()</code>返回被替换的值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// Worker 线程</span>
self<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">event</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> sharedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>event<span class="token punctuation">.</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>i <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">const</span> storedValue <span class="token operator">=</span> Atomics<span class="token punctuation">.</span><span class="token function">store</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> i<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">The item at array index </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>i<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> is now </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>storedValue<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      <span class="token keyword">const</span> exchangedValue <span class="token operator">=</span> Atomics<span class="token punctuation">.</span><span class="token function">exchange</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> i<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">The item at array index </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>i<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> was </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>exchangedValue<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">, now 2</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>上面代码将共享内存的偶数位置的值改成<code>1</code>，奇数位置的值改成<code>2</code>。</p> <p><strong>（3）Atomics.wait()，Atomics.wake()</strong></p> <p>使用<code>while</code>循环等待主线程的通知，不是很高效，如果用在主线程，就会造成卡顿，<code>Atomics</code>对象提供了<code>wait()</code>和<code>wake()</code>两个方法用于等待通知。这两个方法相当于锁内存，即在一个线程进行操作时，让其他线程休眠（建立锁），等到操作结束，再唤醒那些休眠的线程（解除锁）。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// Worker 线程</span>
self<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">event</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> sharedArray <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Int32Array</span><span class="token punctuation">(</span>event<span class="token punctuation">.</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> arrayIndex <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> expectedStoredValue <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">;</span>
  Atomics<span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> arrayIndex<span class="token punctuation">,</span> expectedStoredValue<span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>Atomics<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> arrayIndex<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码中，<code>Atomics.wait()</code>方法等同于告诉 Worker 线程，只要满足给定条件（<code>sharedArray</code>的<code>0</code>号位置等于<code>50</code>），就在这一行 Worker 线程进入休眠。</p> <p>主线程一旦更改了指定位置的值，就可以唤醒 Worker 线程。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>
<span class="token keyword">const</span> newArrayValue <span class="token operator">=</span> <span class="token number">100</span><span class="token punctuation">;</span>
Atomics<span class="token punctuation">.</span><span class="token function">store</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> newArrayValue<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> arrayIndex <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> queuePos <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
Atomics<span class="token punctuation">.</span><span class="token function">wake</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> arrayIndex<span class="token punctuation">,</span> queuePos<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>上面代码中，<code>sharedArray</code>的<code>0</code>号位置改为<code>100</code>，然后就执行<code>Atomics.wake()</code>方法，唤醒在<code>sharedArray</code>的<code>0</code>号位置休眠队列里的一个线程。</p> <p><code>Atomics.wait()</code>方法的使用格式如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> index<span class="token punctuation">,</span> value<span class="token punctuation">,</span> timeout<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>它的四个参数含义如下。</p> <ul><li>sharedArray：共享内存的视图数组。</li> <li>index：视图数据的位置（从0开始）。</li> <li>value：该位置的预期值。一旦实际值等于预期值，就进入休眠。</li> <li>timeout：整数，表示过了这个时间以后，就自动唤醒，单位毫秒。该参数可选，默认值是<code>Infinity</code>，即无限期的休眠，只有通过<code>Atomics.wake()</code>方法才能唤醒。</li></ul> <p><code>Atomics.wait()</code>的返回值是一个字符串，共有三种可能的值。如果<code>sharedArray[index]</code>不等于<code>value</code>，就返回字符串<code>not-equal</code>，否则就进入休眠。如果<code>Atomics.wake()</code>方法唤醒，就返回字符串<code>ok</code>；如果因为超时唤醒，就返回字符串<code>timed-out</code>。</p> <p><code>Atomics.wake()</code>方法的使用格式如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">wake</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> index<span class="token punctuation">,</span> count<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>它的三个参数含义如下。</p> <ul><li>sharedArray：共享内存的视图数组。</li> <li>index：视图数据的位置（从0开始）。</li> <li>count：需要唤醒的 Worker 线程的数量，默认为<code>Infinity</code>。</li></ul> <p><code>Atomics.wake()</code>方法一旦唤醒休眠的 Worker 线程，就会让它继续往下运行。</p> <p>请看一个例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 主线程</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">[</span><span class="token number">37</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// 163</span>
Atomics<span class="token punctuation">.</span><span class="token function">store</span><span class="token punctuation">(</span>ia<span class="token punctuation">,</span> <span class="token number">37</span><span class="token punctuation">,</span> <span class="token number">123456</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Atomics<span class="token punctuation">.</span><span class="token function">wake</span><span class="token punctuation">(</span>ia<span class="token punctuation">,</span> <span class="token number">37</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// Worker 线程</span>
Atomics<span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span>ia<span class="token punctuation">,</span> <span class="token number">37</span><span class="token punctuation">,</span> <span class="token number">163</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>ia<span class="token punctuation">[</span><span class="token number">37</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// 123456</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码中，视图数组<code>ia</code>的第 37 号位置，原来的值是<code>163</code>。Worker 线程使用<code>Atomics.wait()</code>方法，指定只要<code>ia[37]</code>等于<code>163</code>，就进入休眠状态。主线程使用<code>Atomics.store()</code>方法，将<code>123456</code>写入<code>ia[37]</code>，然后使用<code>Atomics.wake()</code>方法唤醒 Worker 线程。</p> <p>另外，基于<code>wait</code>和<code>wake</code>这两个方法的锁内存实现，可以看 Lars T Hansen 的 <a href="https://github.com/lars-t-hansen/js-lock-and-condition" target="_blank" rel="noopener noreferrer">js-lock-and-condition<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> 这个库。</p> <p>注意，浏览器的主线程不宜设置休眠，这会导致用户失去响应。而且，主线程实际上会拒绝进入休眠。</p> <p><strong>（4）运算方法</strong></p> <p>共享内存上面的某些运算是不能被打断的，即不能在运算过程中，让其他线程改写内存上面的值。Atomics 对象提供了一些运算方法，防止数据被改写。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> index<span class="token punctuation">,</span> value<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>Atomics.add</code>用于将<code>value</code>加到<code>sharedArray[index]</code>，返回<code>sharedArray[index]</code>旧的值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">sub</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> index<span class="token punctuation">,</span> value<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>Atomics.sub</code>用于将<code>value</code>从<code>sharedArray[index]</code>减去，返回<code>sharedArray[index]</code>旧的值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">and</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> index<span class="token punctuation">,</span> value<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>Atomics.and</code>用于将<code>value</code>与<code>sharedArray[index]</code>进行位运算<code>and</code>，放入<code>sharedArray[index]</code>，并返回旧的值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">or</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> index<span class="token punctuation">,</span> value<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>Atomics.or</code>用于将<code>value</code>与<code>sharedArray[index]</code>进行位运算<code>or</code>，放入<code>sharedArray[index]</code>，并返回旧的值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>Atomics<span class="token punctuation">.</span><span class="token function">xor</span><span class="token punctuation">(</span>sharedArray<span class="token punctuation">,</span> index<span class="token punctuation">,</span> value<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>Atomic.xor</code>用于将<code>vaule</code>与<code>sharedArray[index]</code>进行位运算<code>xor</code>，放入<code>sharedArray[index]</code>，并返回旧的值。</p> <p><strong>（5）其他方法</strong></p> <p><code>Atomics</code>对象还有以下方法。</p> <ul><li><code>Atomics.compareExchange(sharedArray, index, oldval, newval)</code>：如果<code>sharedArray[index]</code>等于<code>oldval</code>，就写入<code>newval</code>，返回<code>oldval</code>。</li> <li><code>Atomics.isLockFree(size)</code>：返回一个布尔值，表示<code>Atomics</code>对象是否可以处理某个<code>size</code>的内存锁定。如果返回<code>false</code>，应用程序就需要自己来实现锁定。</li></ul> <p><code>Atomics.compareExchange</code>的一个用途是，从 SharedArrayBuffer 读取一个值，然后对该值进行某个操作，操作结束以后，检查一下 SharedArrayBuffer 里面原来那个值是否发生变化（即被其他线程改写过）。如果没有改写过，就将它写回原来的位置，否则读取新的值，再重头进行一次操作。</p></div></div> <!----> <div class="page-edit"><div class="edit-link"><a href="https://github.com/lcfqzd/vuepress-theme-vdoing/edit/master/docs/02.前端/04.ES6笔记/28.ArrayBuffer.md" target="_blank" rel="noopener noreferrer">编辑</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <!----> <!----></div> <div class="page-nav-wapper"><div class="page-nav-centre-wrap"><a href="/noteslibrary/pages/16121351be68691b/" class="page-nav-centre page-nav-centre-prev"><div class="tooltip">异步遍历器</div></a> <a href="/noteslibrary/pages/7188882b8d65af1b/" class="page-nav-centre page-nav-centre-next"><div class="tooltip">最新提案</div></a></div> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/noteslibrary/pages/16121351be68691b/" class="prev">异步遍历器</a></span> <span class="next"><a href="/noteslibrary/pages/7188882b8d65af1b/">最新提案</a>→
      </span></p></div></div></div> <!----></main></div> <div class="footer"><!----> 
  Theme by
  <a href="https://github.com/xugaoyi/vuepress-theme-vdoing" target="_blank" title="本站主题">Vdoing</a> 
    | Copyright © 2018-2023
    <span>LCFQZD | MIT License</span></div> <div class="buttons"><div title="返回顶部" class="button blur go-to-top iconfont icon-fanhuidingbu" style="display:none;"></div> <div title="去评论" class="button blur go-to-comment iconfont icon-pinglun" style="display:none;"></div> <div title="主题模式" class="button blur theme-mode-but iconfont icon-zhuti"><ul class="select-box" style="display:none;"><li class="iconfont icon-zidong">
          跟随系统
        </li><li class="iconfont icon-rijianmoshi">
          浅色模式
        </li><li class="iconfont icon-yejianmoshi">
          深色模式
        </li><li class="iconfont icon-yuedu">
          阅读模式
        </li></ul></div></div> <!----> <!----> <!----></div><div class="global-ui"></div></div>
    <script src="/noteslibrary/assets/js/app.dc0c3d24.js" defer></script><script src="/noteslibrary/assets/js/2.a664539c.js" defer></script><script src="/noteslibrary/assets/js/71.aff6ef6b.js" defer></script>
  </body>
</html>
